<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Success_story
 *
 * @author tuancasi
 */
class Success_storyController extends Controller {

    public function init() {
	if (user()->isGuest) {
	    $this->redirect(SITE_NAME_URL);
	}
    }

    public function actionIndex() {
	$model = new Story();
	$criteria = new CDbCriteria();
	$criteria->with = 'user';
	$criteria->order = 'story_id DESC';
	$iTotalRecord = $model->count($criteria);

	$pages = new CPagination($iTotalRecord);
	$pages->pageSize = Story::TOTAL_RECORD;
	$pages->applyLimit($criteria);

	$this->render('index', array(
	    'aStories' => $model->findAll($criteria),
	    'iTotalRecord' => $iTotalRecord,
	    'pages' => $pages
	));
    }

    public function actionMy_story() {
	$model = new Story();
	if (isset($_GET['Story'])) {
	    $model->attributes = $_GET['Story'];
	}
	$this->render('my_story', array('model' => $model));
    }

    public function actionNew_story() {
	$model = new Story();
	$this->_loadAjaxValidate($model);

	if (isset($_POST['submit'])) {
	    $model->attributes = $_POST['Story'];
	    $model->user_id = user()->id;
	    $model->time_created = time();
	    if ($model->validate()) {
		$model->save();
		$this->redirect(url('success_story/my_story'));
	    }
	}
	$this->render('new_story', array(
	    'model' => $model
	));
    }

    public function _loadAjaxValidate($model) {
	if (isset($_POST['ajax']) && $_POST['ajax'] == 'story-form') {
	    $model->attributes = $_POST['Story'];
	    echo CActiveForm::validate($model);
	    Yii::app()->end();
	}
    }

    public function _loadModel($id) {
	$model = Story::model()->findByPk($id);
	if ($model) {
	    return $model;
	} else {
	    throw new CHttpException(400, 'The page is not found');
	}
    }

    /**
     * delete story
     */
    public function actionDelete($id) {
	$model = $this->_loadModel($id);
	$model->delete($id);
    }

    /**
     * edit story
     */
    public function actionUpdate($id) {
	$model = $this->_loadModel($id);

	$this->_loadAjaxValidate($model);

	if (isset($_POST['submit'])) {
	    $model->text = $_POST['Story']['text'];

	    if ($model->validate()) {
		$model->save();
		Yii::app()->user->setFlash('success', '<div class="alert alert-success">You have updated successfully</div>');
	    }
	}
	$this->render('update', array(
	    'model' => $model
	));
    }

}
